import clonedeep from "lodash.clonedeep";

import type { Menu, ExprType } from "./type";

type ExtractDataResultType = {
  data: any[];
  index: number;
};

/** 提取数据 */
export const extractData = (parent: any, datas: any[], expr: ExprType, index = 0): ExtractDataResultType => {
  const result: ExtractDataResultType = {
    data: [],
    index
  };

  if (Array.isArray(datas)) {
    for (const item of datas) {
      const childrenKey = expr.childrenKey || "";
      const childRen = item[childrenKey];

      const params = clonedeep({ parent, currData: item, index: result.index });
      // const params = { parent, currData: item, index: result.index };
      let isFlag = true;
      if (expr.filter && typeof expr.filter === "function") {
        isFlag = expr.filter(params);
      }
      if (isFlag) {
        let buildData: any = null;
        if (expr.getData && typeof expr.getData === "function") {
          buildData = expr.getData(params);
        }

        if (buildData) {
          if (Array.isArray(expr.deletekKeyData)) {
            expr.deletekKeyData.forEach(delKey => {
              if (buildData instanceof Object && delKey in buildData) {
                delete buildData[delKey];
              }
            });
          }
          result.data.push(buildData);
          result.index++;
        }
      } else {
        // console.log("丢弃: ", parent, datas);
      }

      if (childrenKey && Array.isArray(childRen)) {
        const childRes = extractData(item, childRen, expr, result.index);
        result.data.push(...childRes.data);
        result.index = childRes.index;
      }
    }
  }

  return result;
};

/** 下载文件 */
export const downloadFile = (blob: Blob, fileName: string) => {
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.style.display = "none";
  link.setAttribute("download", decodeURIComponent(fileName));
  link.href = url;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

// 提取出菜单(type === "1"), 非按钮菜单
export function findTypeOneItems(items: Menu[]): Menu[] {
  const result: Menu[] = [];
  for (const item of items) {
    if (item.type === "1") {
      result.push(item);
    }
    if (item.children) {
      result.push(...findTypeOneItems(item.children));
    }
  }
  return result;
}